package com.lyw.idempotentstarter.aspect;


import com.lyw.idempotentstarter.annotation.Idempotent;
import com.lyw.idempotentstarter.bean.IdempotentStorageService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class IdempotentAspect {


    private final IdempotentStorageService idempotentStorageService;

    public IdempotentAspect(IdempotentStorageService idempotentStorageService) {
        this.idempotentStorageService = idempotentStorageService;
    }

    @Pointcut("@annotation(com.lyw.idempotentstarter.annotation.Idempotent)")
    public void pointCut(){}

//    @Before("com.lyw.idempotentstarter.aspect.IdempotentAspect.pointCut()")
//    public void before(JoinPoint joinPoint){
//        System.out.println("before");
//        System.out.println(joinPoint.getSignature());
////        System.out.println(joinPoint.toLongString());
//    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        String[] params = methodSignature.getParameterNames();// 获取参数名称
        Object[] args = joinPoint.getArgs();// 获取参数值
        Idempotent annotation = methodSignature.getMethod().getAnnotation(Idempotent.class);
        // 没有获取到注解实例，直接返回
        if (annotation == null){
            return joinPoint.proceed();
        }
//        Field paramName = Idempotent.class.getDeclaredField("paramName");
//        paramName.setAccessible(true);
//        String paramNameValue = (String) paramName.get(annotation);
        String paramNameValue = annotation.paramName();
        System.out.println("获取到的paramName是"+paramNameValue);
        int index = -1;
        for (int i = 0; i < params.length; i++){
            if (paramNameValue.equals(params[i])){
                index = i;
                break;
            }
        }
        if (index == -1){
            throw new Exception("没有指定的token参数");
        }
        boolean flag = this.confirm((String) args[index]);
        if (flag == false){
            return "Token认证失败";
        }
        return joinPoint.proceed();
    }

    private boolean confirm(String arg) {
        System.out.println("获取到指定token的值是"+arg);
        return idempotentStorageService.del("1", 1L, "path", arg);
    }
}
